package cn.dkdoo.mongodb.repository;

import cn.dkdoo.bean.entity.TestTraUser;
import cn.dkdoo.bean.vo.RemoveRequest;
import cn.dkdoo.mongodb.config.MongodbConfig;
import cn.dkdoo.utils.annotation.DkdTransactional;
import cn.dkdoo.utils.templateDefault.mongo.DefaultMongoTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static org.springframework.data.mongodb.core.query.Criteria.where;

/**
 * @author nicky
 * @date 2021/5/12 下午2:29
 */
@DkdTransactional
@Component
public class MongodbRepository {
    @Resource(name = MongodbConfig.defaultMongoTemplate)
    DefaultMongoTemplate dkdMongoTemplate;

    public TestTraUser findRol(String id) {
        return dkdMongoTemplate.findOneRol(Query.query(where("_id").is(id)), TestTraUser.class);
    }
    public List<TestTraUser> find(Collection<String> ids) {
        return dkdMongoTemplate.find(Query.query(where("_id").in(ids)), TestTraUser.class);
    }

//    @DkdTransactional(propagation = Propagation.NOT_SUPPORTED)//不走事务方法1，使用aop
    public void add(List<TestTraUser> datas) {
        if (CollectionUtils.isEmpty(datas)) {
            datas = new ArrayList<>();
            datas.add(TestTraUser.getOne());
            datas.add(TestTraUser.getOne());
        }
        dkdMongoTemplate.insertAll(datas);
        //dkdMongoTemplate.template.insertAll(datas);//不走事务方法2,使用原始的template
        System.out.println(datas.get(0).getId() + "-Thread.currentThread(): " + Thread.currentThread());
    }

    public void remove(RemoveRequest request) {
        Criteria criteria = new Criteria();
        if (StringUtils.isNoneEmpty(request.getId())) {
            criteria.and("_id").is(request.getId());
        }
        if (StringUtils.isNoneEmpty(request.getName())) {
            criteria.and("name").is(request.getName());
        }
        dkdMongoTemplate.remove(Query.query(criteria), TestTraUser.class);
    }

    public void update(String id, String name) {
        Criteria criteria = new Criteria();
        if (StringUtils.isNoneEmpty(id)) {
            criteria.and("_id").is(id);
        }
        if (StringUtils.isNoneEmpty(name)) {
            criteria.and("name").is(name);
        }

        Update update = new Update();
        update.inc("age", 1);

        dkdMongoTemplate.findAndModify(Query.query(criteria), update, TestTraUser.class);
    }

    @DkdTransactional(propagation = Propagation.NOT_SUPPORTED)
    public void updateSelf(String id, String name) {
        this.update(id, name);
    }

}
